/*
 * This file is a part of the SchemaSpy project (http://schemaspy.sourceforge.net).
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 John Currier
 *
 * SchemaSpy is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * SchemaSpy is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package com.qp.basics.estivate;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import static java.sql.DatabaseMetaData.*;

/**
 * Represents a <a href='http://en.wikipedia.org/wiki/Foreign_key'> Foreign Key
 * Constraint</a> that "ties" a child table to a parent table via foreign and
 * primary keys.
 */
// 这个已经 不是再是简单的foreignkey 的方式了，将用来记录那个foreign，parent，child 所以格子字段的意思要扩展，重新解释下
// parentTable childTable 任然是原来的意思， 但是 parentColumn 与 当前表的columbia名字 的问题怎么解决呢？
// parentColumn 把 名字改了 改成 referColumn child 的处理呢？ targetColum 本表中的 colum
// ？==currentColum ok 这样就统一了
// 只要加一个 childColumn 就行了，其他都不动

public class RelationShip implements Comparable<RelationShip> {
	private String name;
	private Table parentTable;
	private Column parentColumn;// parentColumn ;
	private Table childTable;
	private Column childColumn;// childColumn;
	private Column currentColum;
	private int deleteRule;
	private int updateRule;
	private final static Logger logger = Logger.getLogger(RelationShip.class
			.getName());
	private final static boolean finerEnabled = logger.isLoggable(Level.FINER);

	/**
	 * Construct a foreign key for the specified child table. Relationship
	 * details will be added later.
	 *
	 * @param child
	 * @param name
	 * @param deleteRule
	 */
	RelationShip(String name, Table parentTable, Column parentColumn,
			Table childTable, Column childColumn, Column currentColum,
			int deleteRule, int updateRule) {
		this.name = name;
		this.parentTable = parentTable;
		this.parentColumn = parentColumn;
		this.childTable = childTable;
		this.childColumn = childColumn;
		this.currentColum = currentColum;
		this.deleteRule = deleteRule;
		this.updateRule = updateRule;
	}

	/**
	 * Returns the name of the constraint
	 *
	 * @return
	 */
	public String getName() {
		return name;
	}

	/**
	 * Returns the parent table (the table that contains the referenced primary
	 * key column).
	 *
	 * @return
	 */
	public Table getParentTable() {
		return parentTable;
	}

	/**
	 * Returns the table on the "child" end of the relationship (contains the
	 * foreign key that references the parent table's primary key).
	 *
	 * @return
	 */
	public Table getChildTable() {
		return childTable;
	}

	/**
	 * Returns the delete rule for this constraint.
	 *
	 * @see {@link java.sql.DatabaseMetaData#importedKeyCascade}
	 */
	public int getDeleteRule() {
		return deleteRule;
	}

	/**
	 * Returns <code>true</code> if this constraint should <a
	 * href='http://en.wikipedia.org/wiki/Cascade_delete'>cascade
	 * deletions</code>.
	 *
	 * @return
	 */
	public boolean isCascadeOnDelete() {
		return getDeleteRule() == importedKeyCascade;
	}

	/**
	 * Returns <code>true</code> if the constraint prevents the parent table
	 * from being deleted if child tables exist.
	 *
	 * @return
	 */
	public boolean isRestrictDelete() {
		return getDeleteRule() == importedKeyNoAction
				|| getDeleteRule() == importedKeyRestrict;
	}

	/**
	 * Returns <code>true</code> if the constraint indicates that the foreign
	 * key will be set to <code>null</code> when the parent key is deleted.
	 *
	 * @return
	 */
	public boolean isNullOnDelete() {
		return getDeleteRule() == importedKeySetNull;
	}

	public String getDeleteRuleName() {
		switch (getDeleteRule()) {
		case importedKeyCascade:
			return "Cascade on delete";

		case importedKeyRestrict:
		case importedKeyNoAction:
			return "Restrict delete";

		case importedKeySetNull:
			return "Null on delete";

		default:
			return "";
		}
	}

	public String getDeleteRuleDescription() {
		switch (getDeleteRule()) {
		case importedKeyCascade:
			return "Cascade on delete:\n Deletion of parent deletes child";

		case importedKeyRestrict:
		case importedKeyNoAction:
			return "Restrict delete:\n Parent cannot be deleted if children exist";

		case importedKeySetNull:
			return "Null on delete:\n Foreign key to parent set to NULL when parent deleted";

		default:
			return "";
		}
	}

	public String getDeleteRuleAlias() {
		switch (getDeleteRule()) {
		case importedKeyCascade:
			return "C";

		case importedKeyRestrict:
		case importedKeyNoAction:
			return "R";

		case importedKeySetNull:
			return "N";

		default:
			return "";
		}
	}

	/**
	 * Returns the update rule for this constraint.
	 *
	 * @see {@link java.sql.DatabaseMetaData#importedKeyCascade}
	 */
	public int getUpdateRule() {
		return updateRule;
	}

	/**
	 * Returns <code>true</code> if this is an implied constraint or
	 * <code>false</code> if it is "real".
	 *
	 * Subclasses that implement implied constraints should override this
	 * method.
	 *
	 * @return
	 */
	public boolean isImplied() {
		return false;
	}

	/**
	 * We have several types of constraints. This returns <code>true</code> if
	 * the constraint came from the database metadata and not inferred by
	 * something else. This is different than {@link #isImplied()} in that
	 * implied relationships are a specific type of non-real relationships.
	 *
	 * @return
	 */
	public boolean isReal() {
		return getClass() == RelationShip.class;
	}

	/**
	 * Custom comparison method to deal with foreign key names that aren't
	 * unique across all schemas being evaluated
	 *
	 * @param other
	 *            ForeignKeyConstraint
	 *
	 * @return
	 */
	public int compareTo(RelationShip other) {
		if (other == this)
			return 0;

		int rc = getName().compareToIgnoreCase(other.getName());
		if (rc == 0) {
			// should only get here if we're dealing with cross-schema
			// references (rare)
			String ours = getChildColumn().getTable().getSchema();
			String theirs = other.getChildColumn().getTable().getSchema();
			if (ours != null && theirs != null)
				rc = ours.compareToIgnoreCase(theirs);
			else if (ours == null)
				rc = -1;
			else
				rc = 1;
		}

		return rc;
	}

	/**
	 * Static method that returns a string representation of the specified list
	 * of {@link Column columns}.
	 *
	 * @param columns
	 * @return
	 */
	public static String toString(List<Column> columns) {
		if (columns.size() == 1)
			return columns.iterator().next().toString();
		return columns.toString();
	}

	/**
	 * Returns a string representation of this foreign key constraint.
	 *
	 * @return
	 */
	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder();
		buf.append(childTable.getTableName());
		buf.append('.');
		// buf.append(toString(childColumn));
		buf.append(" refs ");
		buf.append(parentTable.getTableName());
		buf.append('.');
		// buf.append(toString(parentColumn));
		if (parentTable.isRemote()) {
			buf.append(" in ");
			buf.append(parentTable.getSchema());
		}
		if (name != null) {
			buf.append(" via ");
			buf.append(name);
		}

		return buf.toString();
	}

	public Column getParentColumn() {
		return parentColumn;
	}

	public void setParentColumn(Column parentColumn) {
		this.parentColumn = parentColumn;
	}

	public Column getChildColumn() {
		return childColumn;
	}

	public void setChildColumn(Column childColumn) {
		this.childColumn = childColumn;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setParentTable(Table parentTable) {
		this.parentTable = parentTable;
	}

	public void setChildTable(Table childTable) {
		this.childTable = childTable;
	}

	public Column getCurrentColum() {
		return currentColum;
	}

	public void setCurrentColum(Column currentColum) {
		this.currentColum = currentColum;
	}

}
